import express, { Request, Response } from 'express';
import { sseManager } from '../sse/SseManager';
import {processSensorSnapshot} from "../utils/sensor-sampling/processSensorSnapshot";
import { bufferSensorData } from '../utils/sensor-sampling/SensorSnapshotBuffer';
import { AppDataSource } from '../config/database';
import { Device } from '../entity/Device';


const notifyRouter = express.Router();


// 通用推送格式（推送给客户端的）
export interface SsePayload {
  did: string;
  properties: Record<string, any>;
}


// 美的推送结构
export interface MideaNotifyBody {
  applianceCode: string;
  properties: Record<string, any>;
}

// 小米推送结构
export interface XiaomiNotifyBody {
  did: string;
  event?: string;
  data: Record<string, any>;
}

// ----- 工具函数：是否为传感器字段 --------

function containsSensorData(obj: Record<string, any>): boolean {
  const sensorKeys = ['temperature', 'humidity', 'pm25'];
  return sensorKeys.some(key => key in obj);
}


/**
 * 美的推送结构：
 * {
 *   applianceCode: "设备ID",
 *   properties: { power: "ON", mode: "cool" }
 * }
 */
notifyRouter.post('/midea/notify', async (req: Request, res: Response) => {
  // 使用类型断言确保 body 结构正确
  const body = req.body as Partial<MideaNotifyBody>;
  const { applianceCode, properties } = body;

  if (!applianceCode || !properties) {
    res.status(400).json({ code: 400, message: '缺少字段' });
    return;
  }

  // 查找设备对应用户id
  const deviceRepo = AppDataSource.getRepository(Device);
  const device = await deviceRepo.findOne({ where: { did: applianceCode } });
  if (!device) {
    res.status(404).json({ code: 404, message: '设备不存在' });
    return;
  }

  const userId = device.userId;

    // 判断是否是传感器数据并处理采样
  if (containsSensorData(properties)) {
    bufferSensorData(applianceCode, properties, userId); // 缓存采样
    console.log(`[SAMPLE] Midea ${applianceCode} 数据采样至缓存`)
    //res.json({ code: 200, message: 'Midea 传感器数据已缓存' }); // 返回成功响应
    //return;
  }

  const payload: SsePayload = {
    did: applianceCode,
    properties
  };

  // 推送给客户端
  sseManager.sendTo(userId, payload);

  res.json({ code: 200, message: '美的推送成功' });
  return;
});

/**
 * 小米推送结构：
 * {
 *   did: "设备ID",
 *   event: "prop.change",
 *   data: { temperature: 25 }
 * }
 */
notifyRouter.post('/xiaomi/notify', async (req: Request, res: Response) => {
    // 使用类型断言确保 body 结构正确
  const body = req.body as Partial<XiaomiNotifyBody>;
  const { did, data } = body;

  if (!did  || !data) {
    res.status(400).json({ code: 400, message: '缺少字段' });
    return;
  }

  // 查找设备对应用户id
  const deviceRepo = AppDataSource.getRepository(Device);
  const device = await deviceRepo.findOne({ where: { did }});
  if(!device){
    res.status(404).json({ code:404, message: '设备不存在'});
    return;
  }

  const userId = device.userId;


  if (containsSensorData(data)) {
    bufferSensorData(did, data, userId); // 缓存采样
    console.log(`[SAMPLE] Xiaomi ${did} 数据采样至缓存`)
    //res.json({ code: 200, message: 'Xiaomi 传感器数据已缓存' }); // 返回成功响应
    //return;
  }

  const payload: SsePayload = {
    did,
    properties: data
  };

  sseManager.sendTo(userId, payload);

  res.json({ code: 200, message: '小米推送成功' });
  return;
});

// 统一向客户端推送格式：
//{
//    did : "设备id"
//    properties: { power: "ON", mode: "cool" }
// }


export default notifyRouter;
